package com.summer.halfSyncAsync;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Future;

public class SerialAsyncTask extends AsyncTask<String>{
	
	public static void main(String[] args) {
		
		List<SerialAsyncTask> asyncTaskList = new LinkedList<SerialAsyncTask>();
		try {
			for(int i=1;i<=20;i++)
				asyncTaskList.add(new SerialAsyncTask());
			
			int index=0;
			for(SerialAsyncTask asyncTask : asyncTaskList){
				Future<String> result = asyncTask.doSomething("Pattern", index++);
				System.out.println(Thread.currentThread().getName()+"--result:"+result.get());
			}
			Thread.sleep(8000);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected String doInBackground(Object... params) {
		String message = (String) params[0];
		int sequence = (int) params[1];
		System.out.println(Thread.currentThread().getName()+"--doInBackground:["+sequence+"]"+message);
		
		
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		return "message:["+sequence+"]"+message;
	}
	
	@Override
	protected void onPreExecute(Object... params) {
		String message = (String) params[0];
		int sequence = (int) params[1];
		System.out.println(Thread.currentThread().getName()+"--onPreExecute:["+sequence+"]"+message);
	}

	public Future<String> doSomething(String message,int sequence){
		if(sequence < 0){
			throw new IllegalArgumentException("Invalid sequence:"+sequence);
		}
		return dispatch(message,sequence);
	}
}
